import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTabsStore = defineStore('tabs', () => {
  // 存储所有打开的标签页
  const tabs = ref([
    {
      title: '仪表盘',
      path: '/',
      name: 'Dashboard',
      closable: false
    }
  ])

  // 当前激活的标签页
  const activeTab = ref('/')
  
  // 当前正在刷新的标签页路径
  const refreshingTab = ref('')

  // 添加标签页
  const addTab = (route) => {
    // 检查标签是否已存在
    const isExist = tabs.value.some(tab => tab.path === route.path)
    if (!isExist) {
      tabs.value.push({
        title: route.meta.title || '未命名页面',
        path: route.path,
        name: route.name,
        closable: route.path !== '/'
      })
    }
    activeTab.value = route.path
  }

  // 关闭标签页
  const closeTab = (targetPath) => {
    // 如果关闭的是当前激活的标签页，需要激活其他标签页
    if (activeTab.value === targetPath) {
      const targetIndex = tabs.value.findIndex(tab => tab.path === targetPath)
      if (targetIndex > 0) {
        // 激活前一个标签页
        activeTab.value = tabs.value[targetIndex - 1].path
      } else if (tabs.value.length > 1) {
        // 激活下一个标签页
        activeTab.value = tabs.value[1].path
      } else {
        // 默认激活首页
        activeTab.value = '/'
      }
    }
    
    // 从数组中移除标签页
    tabs.value = tabs.value.filter(tab => tab.path !== targetPath)
  }

  // 关闭其他标签页
  const closeOtherTabs = (path) => {
    // 保留首页和当前页
    tabs.value = tabs.value.filter(tab => !tab.closable || tab.path === path)
    activeTab.value = path
  }

  // 关闭所有标签页
  const closeAllTabs = () => {
    // 只保留首页
    tabs.value = tabs.value.filter(tab => !tab.closable)
    activeTab.value = '/'
  }

  // 根据路由更新激活的标签页
  const updateActiveTab = (path) => {
    activeTab.value = path
  }
  
  // 设置正在刷新的标签页
  const setRefreshingTab = (path) => {
    refreshingTab.value = path
  }

  return {
    tabs,
    activeTab,
    refreshingTab,
    addTab,
    closeTab,
    closeOtherTabs,
    closeAllTabs,
    updateActiveTab,
    setRefreshingTab
  }
})